#include "Common.h"
#include <fstream>
#include "IOManager.h"

namespace Audio
{
	namespace IO
	{

		DefaultFile::DefaultFile(const STRING& path)
			:fileName(path)
			,fileHandle(NULL)			
		{

		}
		DefaultFile::~DefaultFile()
		{
			Close();
		}

		BOOL DefaultFile::Eof()
		{
			return fileHandle->eof() ? TRUE : FALSE;
		}

		void DefaultFile::Open(const FileOpenParameters& p)
		{
			fileHandle = new IFStream(fileName.c_str(), std::ios::in | std::ios::binary);
			if(fileHandle->bad())
			{
				throw CanNotOpenFileException();
			}		
		}
		void DefaultFile::Close()
		{
			if(fileHandle)
			{
				fileHandle->close();
				delete fileHandle;
				fileHandle = NULL;
			}
		}

		UINT32 DefaultFile::Read(UINT8* buffer, UINT32 size)
		{
			if(!fileHandle->read((char*)buffer, (std::streamsize)size))
			{
				UINT32 read = (UINT32)fileHandle->gcount();
				if(fileHandle->eof())
				{
					//fileHandle->clear();
					return read;
				}
				else
				{
					throw IOException();
				}
			}
			return (UINT32)fileHandle->gcount();
		}

		void DefaultFile::Seek(UINT32 pos)
		{
			if(!fileHandle->seekg((std::streampos)pos))
			{
				throw IOException();
			}
		}
		UINT32 DefaultFile::Tell()
		{
			return (UINT32)fileHandle->tellg();
		}	


		
		IFile* DefaultFileFactory::CreateFile(const CreateFileParameters& p)
		{
			return new DefaultFile(p.Path);
		}
		void  DefaultFileFactory::DestroyFile(IFile*& f)
		{
			delete f;
			f = NULL;
		}


		IOManager::IOManager()
			:fileFactory(NULL)
		{
			
		}
		IOManager::~IOManager()
		{
			delete fileFactory;
			fileFactory = NULL;
		}

		void IOManager::Init(IFileFactory* f)
		{
			fileFactory = f;
		}

		IFile* IOManager::CreateFile(const CreateFileParameters& p)
		{
			return fileFactory->CreateFile(p);
		}
		void  IOManager::DestroyFile(IFile*& f)
		{
			return fileFactory->DestroyFile(f);
		}
	}
}